package top.majuan.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.majuan.springboot3.base.PageBean;
import top.majuan.springboot3.base.R;
import top.majuan.springboot3.dao.TbSoftwareMapper;
import top.majuan.springboot3.dao.TbSoftwaretypeMapper;
import top.majuan.springboot3.entity.TbSoftware;
import top.majuan.springboot3.entity.TbSoftwaretype;
import top.majuan.springboot3.service.TbSoftwareService;
import top.majuan.springboot3.vo.PageVo;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbSoftwareServiceImpl implements TbSoftwareService {
    public final TbSoftwareMapper tbSoftwareMapper;
    public final TbSoftwaretypeMapper tbSoftwaretypeMapper;

    @Override
    public R<String> insert(TbSoftware tbSoftware) {
        TbSoftwaretype check = tbSoftwaretypeMapper.selectById(tbSoftware.getStid());
        if(check!=null){
            return R.fail("软件类型信息错误",null);
        }
        int i = tbSoftwareMapper.insert(tbSoftware);
        return i==1?R.ok("新增成功",null):R.fail("新增失败",null);
    }

    @Override
    public R<PageVo<TbSoftware>> query(TbSoftware tbSoftware, PageBean pageBean) {
        IPage<TbSoftware> page = new Page<>(pageBean.getPageNumber(),pageBean.getPageSize());
        QueryWrapper<TbSoftware> wrapper = new QueryWrapper<>();
        wrapper.eq(tbSoftware.getStid()!=null,"stid",tbSoftware.getStid());
        wrapper.like(StringUtils.hasText(tbSoftware.getSname()),"sname",tbSoftware.getSname());
        page = tbSoftwareMapper.selectPage(page,wrapper);
        return R.ok(page);
    }

    @Override
    public R<TbSoftware> queryByKey(Integer id) {
        TbSoftware tbSoftware = tbSoftwareMapper.selectById(id);
        return tbSoftware == null ? R.fail("查询失败",null) :R.ok("查询成功",tbSoftware);
    }

    @Override
    public R<String> update(TbSoftware tbSoftware) {
        // 验证班级信息是否正确
        TbSoftwaretype check = tbSoftwaretypeMapper.selectById(tbSoftware.getStid());
        if (check == null){
            return R.fail("软件类型信息错误",null);
        }
        int i = tbSoftwareMapper.updateById(tbSoftware);
        return i==1?R.ok("修改成功",null):R.fail("修改失败",null);
    }

    @Override
    public R<String> delete(Integer id) {
        int i = tbSoftwareMapper.deleteById(id);
        return i==1?R.ok("删除成功",null):R.fail("删除失败",null);
    }
}
